﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class SchoolProductionFormReport : Form
    {
        public SchoolProductionFormReport()
        {
            InitializeComponent();
        }

        int regID, avpID, fhID, pfshID = -1, cultID, prkID, productID;
        tb_schoolproduct schoolProduct;
        const string catMeasure = "Dimension";

        private void SchoolProductionFormReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCulture.DisplayMember = "Name";
            cbCulture.ValueMember = "ID";
            cbCulture.SelectedIndex = -1;
            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);

        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbPFSH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbPFSH.DataSource = null;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
                cbPFSH.Enabled = true;
                cbPFSH.SelectedIndexChanged -= cbPFSH_SelectedIndexChanged;
                cbPFSH.DataSource = DBClass.Schools
                    .Where(wh => wh.FarmID == fhID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbPFSH.DisplayMember = "Name";
                cbPFSH.ValueMember = "ID";
                cbPFSH.SelectedIndex = -1;
                cbPFSH.Text = string.Empty;
                cbPFSH.SelectedIndexChanged += new EventHandler(cbPFSH_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbPFSH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbPFSH.SelectedIndex >= 0)
            {
                pfshID = Convert.ToInt32(cbPFSH.SelectedValue);
                groupBoxPFSH.Enabled = true;
            }
            else
            {
                pfshID = 0;
            }
        }

        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                cbProductKind.SelectedIndexChanged -= cbProductKind_SelectedIndexChanged;

                cultID = Convert.ToInt32(cbCulture.SelectedValue);
                cbProductKind.Enabled = true;

                if (InformationClass.Lang)
                    cbProductKind.DataSource = DBClass.ProductKids
                        .Where(wh => wh.CultureID == cultID)
                        .Select(se => new
                        {
                            Name = se.Name,
                            ID = se.ID
                        }).ToArray();
                else
                    cbProductKind.DataSource = DBClass.ProductKids
                        .Where(wh => wh.CultureID == cultID)
                        .Select(se => new
                        {
                            Name = se.NameUz,
                            ID = se.ID
                        }).ToArray();
                cbProductKind.DisplayMember = "Name";
                cbProductKind.ValueMember = "ID";
                cbProductKind.SelectedIndex = -1;
                cbProductKind.Text = string.Empty;

                cbProductKind.SelectedIndexChanged += new EventHandler(cbProductKind_SelectedIndexChanged);
                productID = 0;
            }
        }

        private void cbProductKind_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbProductKind.SelectedIndex >= 0)
            {
                prkID = Convert.ToInt32(cbProductKind.SelectedValue);

                cbProducts.Enabled = true;
                cbProducts.SelectedIndexChanged -= cbProducts_SelectedIndexChanged;

                if (InformationClass.Lang)
                    cbProducts.DataSource = DBClass.Products
                        .Where(wh => wh.ProductKindID == prkID)
                        .Select(se => new
                        {
                            ID = se.ID,
                            Name = se.Name
                        }).ToArray();
                else
                    cbProducts.DataSource = DBClass.Products
                        .Where(wh => wh.ProductKindID == prkID)
                        .Select(se => new
                        {
                            ID = se.ID,
                            Name = se.NameUz
                        }).ToArray();

                cbProducts.DisplayMember = "Name";
                cbProducts.ValueMember = "ID";
                cbProducts.SelectedIndex = -1;
                cbProducts.Text = string.Empty;
                productID = 0;
                cbProducts.SelectedIndexChanged += new EventHandler(cbProducts_SelectedIndexChanged);
            }
        }

        private void cbProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbProducts.SelectedIndex >= 0)
            {
                productID = Convert.ToInt32(cbProducts.SelectedValue);
            }
            else
                productID = 0;
        }

        private void chbPFSH_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxPFSH.Enabled = chbPFSH.Checked;
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {
            dtpDate.Enabled = chbDate.Checked;
        }

        private void chbProduction_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxProduct.Enabled = chbProduction.Checked;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? sID, prID;
            DateTime? dt;

            if (chbPFSH.Checked && pfshID > 0)
                sID = pfshID;
            else
                sID = null;

            if (chbDate.Checked)
                dt = dtpDate.Value.Date;
            else
                dt = null;

            if (chbProduction.Checked && productID > 0)
                prID = productID;
            else
                prID = null;

            dgvSchoolProduction.DataSource = DBClass.RESPContext.SchoolProductReport(InformationClass.Lang, sID, prID, dt);

            if (InformationClass.Lang)
            {
                dgvSchoolProduction.Columns["Date"].HeaderText = "Дата";
                dgvSchoolProduction.Columns["Name"].HeaderText = "Название ПФШ";
                dgvSchoolProduction.Columns["Area"].HeaderText = "Площадь га.";
                dgvSchoolProduction.Columns["ProductName"].HeaderText = "Название продукции";
                dgvSchoolProduction.Columns["Measure"].HeaderText = "Ед. измерения";
                dgvSchoolProduction.Columns["HarvestQuantity"].HeaderText = "Количество собранного урожая";
                dgvSchoolProduction.Columns["Cost"].HeaderText = "Общая стоимость (тыс.сум)";
            }
            else
            {
                dgvSchoolProduction.Columns["Date"].HeaderText = "Сана";
                dgvSchoolProduction.Columns["Name"].HeaderText = "ДФМ номи";
                dgvSchoolProduction.Columns["Area"].HeaderText = "Майдон (га)";
                dgvSchoolProduction.Columns["ProductName"].HeaderText = "Маҳсулот номи";
                dgvSchoolProduction.Columns["Measure"].HeaderText = "Ўлчов бирлиги";
                dgvSchoolProduction.Columns["HarvestQuantity"].HeaderText = "Йиғиб олинган маҳсулот миқдори";
                dgvSchoolProduction.Columns["Cost"].HeaderText = "Умумий нарҳи, миллий валютада (минг сўм)";
            }

            dgvSchoolProduction.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSchoolProduction.AutoResizeColumns();
        }

        private void dgvSchoolProduction_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvSchoolProduction.Columns.IndexOf(dgvSchoolProduction.Columns["Measure"]))
            {
                if (e.Value == null)
                    return;
                else
                {
                    if ((int)e.Value == 0)
                        e.Value = "NO DATA";
                    else
                        e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catMeasure);
                }
            }
            if (e.ColumnIndex == dgvSchoolProduction.Columns.IndexOf(dgvSchoolProduction.Columns["Cost"]) && e.Value != null)
            {
                e.Value = ((decimal)e.Value).ToString("N2");
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvSchoolProduction.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelapp.Visible = true;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i18.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i18uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int numPage = 1, left = 1, top = 11;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(numPage);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbPFSH.Checked)
            {
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                excelworksheet.Cells[5, 3] = cbAVP.Text;
                excelworksheet.Cells[6, 3] = cbFH.Text;
                excelworksheet.Cells[7, 3] = cbPFSH.Text;
            }

            string yr = InformationClass.Lang ? "Год: " : "Йил: ";
            if (chbDate.Checked)
                excelworksheet.Cells[9, 2] = yr + dtpDate.Value.Year.ToString();

            if (chbProduction.Checked)
                excelworksheet.Cells[9, 4] = cbCulture.Text;



            for (int i = 0; i < dgvSchoolProduction.Rows.Count; i++)
            {

                excelworksheet.Cells[i + top, 3] = dgvSchoolProduction["Date", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, 3]);

                for (int j = 3; j < dgvSchoolProduction.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + top, dgvSchoolProduction.Columns[j].DisplayIndex + left] = dgvSchoolProduction[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + top, dgvSchoolProduction.Columns[j].DisplayIndex + left]);
                }
                excelworksheet.Cells[i + top, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + top, 2]);
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(numPage);
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvSchoolProduction.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvSchoolProduction);
        }
    }
}
